<?php
namespace addons\mall\controller;

/**
   * 商品控制器
 */
class Goods extends Base{

    public function _initialize() {
        parent::_initialize();
        $this->model = new \app\common\model\mall\goods\Goods;

    }
    /**
     * 获取商品列表
     */
    public function index()
    {
        $searchword = $this->request->param('searchword');
        $pagesize = $this->request->param('pagesize/d',16);
        $this->assign('pagesize',$pagesize);

        $filterlist = [];
        $orderlist = [];

        $filter = $this->request->get('filter/a',[]);
        $orderby = $this->request->get('orderby', '');
        $orderway = $this->request->get('orderway', '', 'strtolower');
        $params = ['pagesize' => $pagesize];
        //$params = ['pagesize' => $pagesize, 'id' => $cat->id];
        if ($filter)
            $params['filter'] = $filter;
        if ($orderby)
            $params['orderby'] = $orderby;
        if ($orderway)
            $params['orderway'] = $orderway;

        $fields = [
            ['name' => 'goods_tag', 'title' => '商品标签', 'content' => ['bestis'=>__("bestis"), 'hotis'=>__("Hotis"), 'newis'=>__("Newis"), 'recomis'=>__("Recomis")]],
        ];
        $filter = array_intersect_key($filter, array_flip(array_column($fields, 'name')));
        foreach ($fields as $v) {
            $content = [];
            $all = ['' => __('All')] + $v['content'];
            foreach ($all as $m => $n) {
                $active = ($m === '' && !isset($filter[$v['name']])) || (isset($filter[$v['name']]) && $filter[$v['name']] == $m) ? TRUE : FALSE;
                $prepare = $m === '' ? array_diff_key($filter, [$v['name'] => $m]) : array_merge($filter, [$v['name'] => $m]);
                $url = '?' . http_build_query(array_merge(['filter' => $prepare], array_diff_key($params, ['filter' => ''])));
                $content[] = ['value' => $m, 'title' => $n, 'active' => $active, 'url' => $url];
            }
            $filterlist[] = [
                'name'    => $v['name'],
                'title'   => $v['title'],
                'content' => $content,
            ];
        }


        $sortrank = [
            ['name' => 'id', 'title' => __('Default')],
            ['name' => 'visitnum', 'title' => __('Visitnum')],
            ['name' => 'salenum', 'title' => __('Salenum')],
            ['name' => 'shopprice', 'title' => __('Shopprice')],
            ['name' => 'appraisenum', 'title' => __('Appraisenum')],
            ['name' => 'saletime', 'title' => __('Saletime')],
        ];
        $orderby = $orderby && in_array($orderby, ['id', 'visitnum', 'salenum', 'shopprice', 'appraisenum', 'saletime']) ? $orderby : 'id';
        $orderway = $orderway ? $orderway : 'desc';
        foreach ($sortrank as $k => $v) {
            $url = '?' . http_build_query(array_merge($params, ['orderby' => $v['name'], 'orderway' => ($orderway == 'desc' ? 'asc' : 'desc')]));
            $v['active'] = $orderby == $v['name'] ? true : false;
            $v['url'] = $url;
            $orderlist[] = $v;
        }

        foreach($filter as $k=>$v){
            if($k=="goods_tag") {
                $filter[$v] = 1;
                unset($filter[$k]);
            }
        }
        if($searchword){
            $w = [];
            $w["goodsname"] = ["like", "%" . $searchword . "%"];
            $shop_id = $this->request->param('shop_id');
            if($shop_id){
                $w['shop_id'] = $shop_id;
            }
            $pagelist = $this->model->where('status', 'in','sale,warn')
                ->field('id,shop_id,goodsname,shopprice,goodsimg,bestis,hotis, newis,recomis,salenum,saletime,visitnum,appraisenum')
                ->where($w)
                ->paginate($pagesize, false, ['type' => '\\addons\\mall\\library\\Bootstrap']);
        }else{
            $pagelist = $this->model->where('status', 'in','sale,warn')
                ->field('id,shop_id,goodsname,shopprice,goodsimg,bestis,hotis, newis,recomis,salenum,saletime,visitnum,appraisenum')
                ->where($filter)
                ->order($orderby, $orderway)
                ->paginate($pagesize, false, ['type' => '\\addons\\mall\\library\\Bootstrap']);

        }
        //处理关注
        if(cookie('uid')){
            $f = model('\app\common\model\mall\user\Favorite');
            foreach($pagelist as $k=>$v){
                $pagelist[$k]['favShop'] = $f->checkFavorite($v['shop_id'],'shop');
                $pagelist[$k]['favGood'] = $f->checkFavorite($v['id'],'goods');
            }
        }

        $pagelist->appends($params);
        $this->view->assign("__FILTERLIST__", $filterlist);
        $this->view->assign("__ORDERLIST__", $orderlist);
        $this->view->assign("__PAGELIST__", $pagelist);
        //$this->view->assign("__CAT__", $cat);
        return $this->fetch();
    }

    /**
     * 查看商品详情
     */
    public function detail(){
        $goods = $this->model->getBySale((int)$this->request->param('ids'));
        if(!empty($goods)){
            $history = cookie("history_goods");
            $history = is_array($history)?$history:[];
            array_unshift($history, (string)$goods['id']);
            $history = array_values(array_unique($history));
            
            if(!empty($history)){
                cookie("history_goods",$history,25920000);
            }

            $goodscat_id = explode(",", $goods['goodscat_ids']);
            $goods['goodscat_ids'] = end($goodscat_id);
            $this->assign('goods',$goods);
            $this->assign('shop',$goods['shop']);
            $this->assign('consultType',model("Consult","common\model\mall\goods")->getTypeList());
            return $this->fetch();
        }else{
            $this->error(__('No Results were found'));
        }
    }

    /**
     * 查看商品概要
     */
    public function quickView(){
        $goods = $this->model->getBySale((int)$this->request->param('ids'));
        if(!empty($goods)){
            $history = cookie("history_goods");
            $history = is_array($history)?$history:[];
            array_unshift($history, (string)$goods['id']);
            $history = array_values(array_unique($history));

            if(!empty($history)){
                cookie("history_goods",$history,25920000);
            }
            $goodscat_id = explode(",", $goods['goodscat_ids']);
            $goods['goodscat_ids'] = end($goodscat_id);
            $this->assign('goods',$goods);
            $this->assign('shop',$goods['shop']);
            return $this->fetch();
        }else{
            $this->error(__('No Results were found'));
        }
    }

    /**
     *  记录对比商品
     */
    public function contrastGoods(){
        $id = (int)input('post.id');
        $contras = cookie("contras_goods");
        if($id>0){
            if(isset($contras['list']) && count($contras['list'])>3) $this->error("对比栏已满");
            $goods = $this->model->getBySale($id);
            $cat_id = explode(',',$goods['goodscat_ids']);
            $cat_id = $cat_id[0];
            if(count($contras['list'])==0) unset($contras['cat_id']);//没有商品时，清除分类
            if(isset($contras['cat_id']) && $cat_id!=$contras['cat_id']) $this->error('请选择同分类对比');
            if(!isset($contras['cat_id']))$contras['cat_id'] = $cat_id;
            $contras['list'][$id] = $id;
            cookie("contras_goods",$contras,25920000);
            $this->success("添加成功");
        }

    }

    public function loadContrastGoods(){
        $contras = cookie("contras_goods");
        $list = [];
        if(isset($contras['list'])){
            foreach($contras['list'] as $v){
                $list[] = $this->model->getBySale($v);
            }
        }
        $this->success("加载成功", null, ['list' => $list]);

    }

    /**
     *  删除对比商品
     */
    public function contrastDel(){
        $id = (int)input('post.id');
        $contras = cookie("contras_goods");
        if($id>0 && isset($contras['list'])){
            unset($contras['list'][$id]);
            cookie("contras_goods",$contras,25920000);
        }else{
            cookie("contras_goods", null);
        }
        $this->success('删除成功');
    }
    /**
     *  商品对比
     */
    public function compare(){
        $contras = cookie("contras_goods");
        $list = $lists= $saleSpec = $shop = $score = $brand = $spec = [];
        if(isset($contras['list'])){
            foreach($contras['list'] as $value){
                $dara = $this->model->getBySale($value);
                if(isset($dara['saleSpec'])){
                    foreach($dara['saleSpec'] as $ks=>$vs){
                        if($vs['defaultis']==1){
                            $dara['defaultSpec'] = $vs;
                            $dara['defaultSpec']['ids'] = explode(':',$ks);
                        }
                    }
                    $saleSpec[$value] = $dara['saleSpec'];
                }
                $list[] = $dara;
            }
            //第一个商品信息
            $goods = $list[0];
            //对比处理
            $data = $shops = $scores = $brands = [];
            $shops['identical'] = $scores['identical'] = $brands['identical'] = 1;
            foreach($list as $v){
                $shop[$v['id']] = $v['shop']['name'];
                if($goods['shop']['shop_id']!=$v['shop']['shop_id'])$shops['identical'] = 0;
                $score[$v['id']] = $v['raty']['totalScore'];
                if($goods['raty']['totalScore']!=$v['raty']['totalScore']) $scores['identical'] = 0;
                $brand[$v['id']] = $v['brandName'];
                if($goods['brand_id']!=$v['brand_id'])$brands['identical'] = 0;
                if(isset($v['spec'])){
                    foreach($v['spec'] as $k2=>$v2){
                        $spec[$k2]['identical'] = 0;
                        $spec[$k2]['type'] = 'spec';
                        $spec[$k2]['name'] = $v2['name'];
                        $spec[$k2]['cat_id'] = $k2;
                        foreach($v2['list'] as $ks22=>$vs22){
                            $v['spec'][$k2]['list'][$ks22]['isDefault'] = (in_array($vs22['itemId'],$v['defaultSpec']['ids']))?1:0;
                        }
                        $spec[$k2]['info'][$v['id']] = $v['spec'][$k2];
                    }
                }
            }
            $shops['name'] = '店铺';
            $shops['type'] = 'shop';
            $shops['info'] =  $shop;
            $lists[] = $shops;
            $scores['name'] = '商品评分';
            $scores['type'] = 'score';
            $scores['info'] =  $score;
            $lists[] = $scores;
            $brands['name'] = '品牌';
            $brands['type'] = 'brand';
            $brands['info'] =  $brand;
            $lists[] = $brands;
            foreach($spec as $v3){
                $lists[] = $v3;
            }
        }
        $data['list'] = $list;
        $data['lists'] = $lists;
        $data['saleSpec'] = $saleSpec;
        $this->assign('data',$data);
        return $this->fetch();
    }

    /**
     * 根据商品id取评论（tab页面）
     */
    public function getAppraiseByGoodsId(){
        // 处理匿名
        $anonymous = (int)input('anonymous',1);
        $goodsId = (int)input('goodsId');
        $where = ['ga.goods_id'=>$goodsId];
        // 筛选条件
        $type = input('type');
        $filterWhere = '';
        switch ($type) {
            case 'pic':// 晒图
                $filterWhere = " ga.receivimg <> '' ";
                break;
            case 'best':// 好评
                $filterWhere = "(ga.goodsraty+ga.serviceraty+ga.timeraty)>=15*0.9";
                break;
            case 'good':// 中评
                $filterWhere = "(ga.goodsraty+ga.serviceraty+ga.timeraty)>=15*0.6 and (ga.goodsraty+ga.serviceraty+ga.timeraty)<15*0.9";
                break;
            case 'bad':// 差评
                $filterWhere = "(ga.goodsraty+ga.serviceraty+ga.timeraty)<15*0.6";
                break;
        }
        $appModel = new \addons\mall\model\Appraise();
        $rs = $appModel->alias('ga')
            ->field('ga.id,ga.content,ga.receivimg,ga.reply,ga.replytime,ga.createtime,ga.goodsraty,
                    ga.serviceraty,ga.timeraty,ga.shop_id,ga.order_id,ga.goods_id,ga.showis,
                    s.name,u.avatar,u.nickname,u.username,u.score,og.goodsSpecNames')
            ->join('__USER__ u','ga.user_id=u.id','left')
            ->join('__MALL_ORDER_GOODS__ og','og.order_id=ga.order_id and og.id=ga.ordergoods_id and og.goods_id=ga.goods_id','inner')
            ->join('__MALL_SHOP_SHOP__ s','ga.shop_id=s.id','inner')
            ->where($where)
            ->where($filterWhere)
            ->order('ga.id desc')
            ->paginate(input('pagesize/d'));

        //生成分页元素，准备ajax调用
        $pagination = $rs->render();
        $list = $rs->items();
        foreach($list as $k=>$v){
            // 格式化时间
            $list[$k]['createTime'] = date('Y-m-d',strtotime($v['createtime']));
            $list[$k]['goodsSpecNames'] = str_replace('@@_@@','，',$v['goodsSpecNames']);
            // 总评分
            $list[$k]['avgScore'] = round(($v['goodsraty'] + $v['serviceraty'] + $v['timeraty'])/3,0);
            if($anonymous){
                $loginName = $v['nickname']?$v['nickname']:$v['username'];
                $start = floor((strlen($loginName)/2))-1;
                $list[$k]['loginName'] = substr_replace($loginName,'***',$start,3);
            }
            //获取用户等级
            $rrs = $this->auth->getlevel();
            $list[$k]['userTotalScore'] = $rrs['level_img'];
            $list[$k]['rankName'] = empty($rrs['level_name'])?' ':$rrs['level_name'];
        }
        $rs->appends($list);
        // 获取该商品 各评价数
        $eachApprNum = $appModel->getGoodsEachApprNum($goodsId);
        $rs['bestNum'] = $eachApprNum['best'];
        $rs['goodNum'] = $eachApprNum['good'];
        $rs['badNum'] = $eachApprNum['bad'];
        $rs['picNum'] = $eachApprNum['pic'];
        $rs['sum'] = $eachApprNum['sum'];
        if($rs!==false){
            $rs["pagination"] = $pagination;
            $this->success("",null, $rs);
        }else{
            $this->error($this->getError());
        }
    }

    /**
     * 商品评价详情(独立页面)
     */
    public function appraise(){
        // 处理匿名
        $anonymous = (int)input('anonymous',1);
        $goodsid = (int)$this->request->get('goodsid');
        $searchword = $this->request->param('searchword');
        $pagesize = $this->request->get('pagesize',10);

        $filterlist = [];
        $orderlist = [];

        $filter = $this->request->get('filter');
        if(!$filter)$filter=[];
        $orderby = $this->request->get('orderby', '');
        $orderway = $this->request->get('orderway', '', 'strtolower');
        $params = ['pagesize' => $pagesize];//, 'id' => $cat->id
        if ($goodsid)
            $params['goodsid'] = $goodsid;
        if ($filter)
            $params['filter'] = $filter;
        if ($orderby)
            $params['orderby'] = $orderby;
        if ($orderway)
            $params['orderway'] = $orderway;

        $statusList = ['imgs'=>__('Receivimg'),'best'=>__('Best'),'good'=>__('Good'),'bad'=>__('Bad')];

        $fields = [
            ['name' => 'status', 'title' => '', 'content' => $statusList],
        ];
        $filter = array_intersect_key($filter, array_flip(array_column($fields, 'name')));
        foreach ($fields as $v) {
            $content = [];
            $all = ['' => __('All')] + $v['content'];
            foreach ($all as $m => $n) {
                $active = ($m === '' && !isset($filter[$v['name']])) || (isset($filter[$v['name']]) && $filter[$v['name']] == $m) ? TRUE : FALSE;
                $prepare = $m === '' ? array_diff_key($filter, [$v['name'] => $m]) : array_merge($filter, [$v['name'] => $m]);
                $url = '?' . http_build_query(array_merge(['filter' => $prepare], array_diff_key($params, ['filter' => ''])));
                $content[] = ['value' => $m, 'title' => $n, 'active' => $active, 'url' => $url];
            }
            $filterlist[] = [
                'name'    => $v['name'],
                'title'   => $v['title'],
                'content' => $content,
            ];
        }

        $sortrank = [
            ['name' => 'id', 'title' => __('Default')],
            ['name' => 'goodsraty', 'title' => __('Goodsscore')],
            ['name' => 'serviceraty', 'title' => __('Servicescore')],
            ['name' => 'timeraty', 'title' => __('Timescore')],
        ];
        //设置排序默认值
        $orderby = $orderby && in_array($orderby, ['money', 'name', 'id']) ? $orderby : 'money';
        $orderway = $orderway ? $orderway : 'desc';
        //构建排序数组，以供前端使用
        foreach ($sortrank as $k => $v) {
            $url = '?' . http_build_query(array_merge($params, ['orderby' => $v['name'], 'orderway' => ($orderway == 'desc' ? 'asc' : 'desc')]));
            $v['active'] = $orderby == $v['name'] ? true : false;
            $v['url'] = $url;
            $orderlist[] = $v;
        }

        foreach($filter as $k=>$v){
            if ($k == 'status') {
                if($v=="imgs") $filter[] = ['receivimg','<>',""];
                else $filter[] = ["ga.".$k,'=',$v];
            }else{
                $filter[] = [$k,'=',$v];
            }
            unset($filter[$k]);
        }
        $appModel = new \addons\mall\model\Appraise();
        if($searchword){
            $pagelist = $appModel::alias('ga')
                ->field('ga.id,ga.content,ga.receivimg,ga.reply,ga.replytime,ga.createtime,ga.goodsraty,
                    ga.serviceraty,ga.timeraty,ga.shop_id,ga.order_id,ga.goods_id,ga.showis,
                    s.name,u.avatar,u.nickname,u.username,u.score,og.goodsSpecNames')
                ->join('__USER__ u','ga.user_id=u.id','left')
                ->join('__MALL_ORDER_GOODS__ og','og.order_id=ga.order_id and og.id=ga.ordergoods_id and og.goods_id=ga.goods_id','inner')
                ->join('__MALL_SHOP_SHOP__ s','ga.shop_id=s.id','inner')
                ->where(['ga.goods_id'=>$goodsid])
                ->where("content","like","%".$searchword."%")
                ->paginate($pagesize, false, ['type' => '\\addons\\mall\\library\\Bootstrap','path'=>'javascript:queryByPage([PAGE])']);

        }else {
            $pagelist = $appModel::alias('ga')
                ->field('ga.id,ga.content,ga.receivimg,ga.reply,ga.replytime,ga.createtime,ga.goodsraty,
                    ga.serviceraty,ga.timeraty,ga.shop_id,ga.order_id,ga.goods_id,ga.showis,
                    s.name,u.avatar,u.nickname,u.username,u.score,og.goodsSpecNames')
                ->join('__USER__ u','ga.user_id=u.id','left')
                ->join('__MALL_ORDER_GOODS__ og','og.order_id=ga.order_id and og.id=ga.ordergoods_id and og.goods_id=ga.goods_id','inner')
                ->join('__MALL_SHOP_SHOP__ s','ga.shop_id=s.id','inner')
                ->where(['ga.goods_id'=>$goodsid])
                ->where($filter)
                ->order($orderby, $orderway)
                ->paginate($pagesize, false, ['path'=>'javascript:queryByPage([PAGE])']);
        }

        $list = $pagelist->items();
        foreach ($list as $k =>$v){
        	$v=collection($v)->toArray();
            // 格式化时间
            $list[$k]['createTime'] = date('Y-m-d',strtotime($v['createtime']));
            $list[$k]['goodsSpecNames'] = str_replace('@@_@@','，',$v['goodsSpecNames']);
            // 总评分
            $list[$k]['avgScore'] = ceil(($v['goodsraty'] + $v['serviceraty'] + $v['timeraty'])/3);
            if($anonymous){
                $loginName = $v['nickname']?$v['nickname']:$v['username'];
                $start = floor((strlen($loginName)/2))-1;
                $list[$k]['loginName'] = substr_replace($loginName,'***',$start,3);
            }
            //获取用户等级
            $rrs = $this->auth->getlevel();
            $list[$k]['userTotalScore'] = $rrs['level_img'];
            $list[$k]['rankName'] = empty($rrs['level_name'])?' ':$rrs['level_name'];
        }
        $pagelist->appends($list);
        $pagelist->appends($params);

        // 获取该商品 各评价数
        $eachApprNum = $appModel->getGoodsEachApprNum($goodsid);
        $appCount['allNum'] = $eachApprNum['sum'];
        $appCount['bestNum'] = $eachApprNum['best'];
        $appCount['goodNum'] = $eachApprNum['good'];
        $appCount['badNum'] = $eachApprNum['bad'];
        $appCount['imgsNum'] = $eachApprNum['pic'];
        $appCount["best_percent"] = (int)($appCount['bestNum'] / $appCount['allNum'] * 100);
        $appCount["good_percent"] = (int)($appCount['goodNum'] / $appCount['allNum'] * 100);
        $appCount["bad_percent"] = 100-$appCount['best_percent']-$appCount['good_percent'];

        $this->view->assign("__FILTERLIST__", $filterlist);
        $this->view->assign("__ORDERLIST__", $orderlist);
        $this->view->assign("__PAGELIST__", $pagelist);
        $this->view->assign('pagesize',$pagesize);
        $this->view->assign("goodsid", $goodsid);
        $this->view->assign("appCount", $appCount);

        return $this->fetch();
    }

    /**
     * 根据商品id取咨询（tab页面）
     */
    public function getConsultByGoodsId(){
        $goodsId = (int)input('goods_id');
        $type = (int)input('type');
        $consultKey = input('consultKey');
        $where = [];
        $where[] = ['gc.status', '=', "normal"];
        $where[] = ['gc.showis', '=', 1];
        $where[] = ['gc.goods_id', '=', $goodsId];
        // 筛选类别
        if($type>0) $where[] = ['gc.type','=',$type];
        // 关键字搜索
        if($consultKey!=''){$where[] = ['gc.content','like',"%$consultKey%"];}
        $rs = \app\common\model\mall\goods\Consult::alias('gc')
            ->join('__USER__ u','u.id=gc.user_id','left')
            ->field('gc.*,u.nickname,u.username')
            ->where($where)
            ->order('gc.createtime desc')
            ->paginate(input('pagesize/d',5),false,[
                'path'     => 'javascript:queryConsult([PAGE])',
            ]);
        //生成分页元素，准备ajax调用
        $pagination = $rs->render();
        $rs = collection($rs)->toArray();

        if(!empty($rs['data'])){
            foreach($rs['data'] as $k=>&$v){
                // 解义
                $v['content'] = htmlspecialchars_decode($v['content']);
                // 处理匿名
                if($v['user_id']>0){
                    // 替换中间两个字符
                    $loginName = $v['nickname']?$v['nickname']:$v['username'];
                    $start = floor((strlen($loginName)/2))-1;
                    $v['loginName'] = substr_replace($loginName,'***',$start,3);
                }
            }
        }
        $rs["pagination"] = $pagination;
        $this->success('', null, $rs);
    }

    /**
     * 进行商品搜索
     */
    public function search(){
        //获取商品记录
        $data = [];
        $data['isStock'] = input('isStock/d');
        $data['isNew'] = input('isNew/d');
        $data['freighttype'] = input('freighttype/d');
        $data['orderBy'] = input('orderBy/d');
        $data['order'] = input('order/d',1);
        $data['keyword'] = input('keyword');
        $data['sprice'] = input('sprice/d');
        $data['eprice'] = input('eprice/d');

        $data['areaId'] = (int)input('areaId');
        $aModel = new \app\common\model\Area;

        // 获取地区
        $data['area1'] = $data['area2'] = $data['area3'] = $aModel->listQuery(); // 省级

        // 如果有筛选地区 获取上级地区信息

        if($data['areaId']!==0){
            $areaIds = $aModel->getParentIds($data['areaId']);
            /*
             2 => int 440000
             1 => int 440100
             0 => int 440106
             */
            $selectArea = [];
            $areaName = '';
            foreach($areaIds as $v){
                $a = $aModel->getById($v);
                $areaName .=$a['areaName'];
                $selectArea[] = $a;
            }
            // 地区完整名称
            $selectArea['areaName'] = $areaName;
            // 当前选择的地区
            $data['areaInfo'] = $selectArea;
            $data['area2'] = $aModel->listQuery($areaIds[2]); // 广东的下级

            $data['area3'] = $aModel->listQuery($areaIds[1]); // 广州的下级
        }

        $data['goodsPage'] = $this->model->pageQuery();
        return $this->fetch("search",$data);
    }

}
